// 加载FORM表单扩展
layui.use(['form'], function(){
	var form = layui.form()
	,layer = layui.layer;

	//监听计费方式选择
	form.on('radio(charge)', function(data){
		var dataState = [ "cpd", "cpm", "cpc"],
		currState = $(data.elem).attr('data-state');

		if( !!($.inArray(currState, dataState) + 1)  == false ) {
			$(".rate-box, .discount-box").hide();
			return false;
		}
		$(".rate-box").removeClass (function (index, classText) {
			return (classText.match (/state\S*/g) || []).join(' ');
		});

		$(".rate-box").addClass("state-" + currState);
		$(".rate-box, .discount-box").show();
	});
	
	//自定义验证规则
	form.verify({
		code_name: function(value){
			if(value.length < 1) {
				return '请填写代码位名称';
			}
		  
		}
		,media: function(value){
			if(+value < 1) {
				return '请选择媒体';
			}
		}
		,size_width: function(value){
			if(+value < 1) {
				return '代码位宽度必须大于1';
			}
		}
		,size_height: function(value){
			if(+value < 1) {
				return '代码位高度必须大于1';
			}
		}
		,rate: function(value) {
			var chargeVal = $('input[name="charge"]:checked ').val();
			if( +chargeVal > 0 && +value <= 0 ) {
				return '请填写刊例价';
			}
		}
		,discount: function(value) {
			var chargeVal = $('input[name="charge"]:checked ').val();
			if( +chargeVal > 0 && +value <= 0 ) {
				return '请填写折扣率';
			}
		}
	});
	
    form.on('submit(submit)', function(data){
		 $.ajax({
          url: "/Code/edit",
          type: "post",
          data:data.field ,
          dataType: "json",
          success: function (msg) {
              if (msg.status == "success") {
				PopModel.refreshParentFrame();
              } else {
                layer.msg(msg.msg, {icon: 5, shift: 6}, function(){});
              }
          }
		});
    });

    //监听select
	form.on('select(media)', function(data){
		var media_id =data.value;
		$.ajax({
			url: "/Code/MediaTogroup",
			type: "post",
			data: {'id':media_id} ,
			dataType: "json",
			success: function (msg) {
			  if(msg.status == 'success') {

				  $("#group_id").empty();
				  $("#group_id").append(msg.codegroup);
				  form.render(); 
			  } else {
				  console.log('有错误了!');
			  }
			}
		});
    });
	// 刷新表单
	form.render();
});
